using System;

namespace BOL.Maths.LinearAlgebra
{
	/// <summary>
    /// Eigenvalues and eigenvectors of a real matrix. 
	/// If A is symmetric, then A = V*D*V' where the eigenvalue matrix D is
	/// diagonal and the eigenvector matrix V is orthogonal.
	/// I.e. A = V.Multiply(D.Multiply(V.Transpose())) and 
	/// V.Multiply(V.Transpose()) equals the identity matrix.
	/// If A is not symmetric, then the eigenvalue matrix D is block diagonal
	/// with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues,
	/// lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda].  The
	/// columns of V represent the eigenvectors in the sense that A*V = V*D,
	/// i.e. A.Multiply(V) equals V.Multiply(D).  The matrix V may be badly
	/// conditioned, or even singular, so the validity of the equation
	/// A = V*D*Inverse(V) depends upon V.cond().
	/// </summary>
	public sealed class EigenvalueDecomposition : DecompositionBase
	{
		#region	 Private variables
		
		private bool _isSymmetric; // symmetry flag
        private double[] _real, _imaginary; // vectors for internal storage of eigenvalues.
        private double[][] _v; // eigen matrix.
        private double[][] _hessenberg; // nonsymmetric Hessenberg form.
        private double[] _ortho; // nonsymmetric algorithm. 
        private double _cdivr, _cdivi;

		#endregion

		#region Public Properties

        /// <summary>Returns the _real parts of the eigenvalues. real(diag(D))</summary>
        public double[] RealEigenvalues { get { return _real; } }

        /// <summary>Returns the _imaginary parts of the eigenvalues. imag(diag(D))</summary>
        public double[] ImaginaryEigenvalues { get { return _imaginary; } }

		/// <summary>Returns the block diagonal eigenvalue matrix. D</summary>
		public double[][] BlockDiagonalEigenMatrix
		{
			get
			{
                int i, j;
                double[][] temp = new double[_n][];

				for (i = 0; i < _n; i++)
				{
                    temp[i] = new double[_n];

                    for (j = 0; j < _n; j++)
                    {
                        if (i == j)
                            temp[i][j] = _real[i];
                        else
                            temp[i][j] = 0.0;
                    }

					if (_imaginary[i] > 0)
						temp[i][i + 1] = _imaginary[i];
                    else if (_imaginary[i] < 0)
						temp[i][i - 1] = _imaginary[i];
				}

                return temp;
			}
		}

        /// <summary>Returns the eigenvector matrix</summary>
        public double[][] V { get { return _v; } }

		#endregion

		#region Constructor

        /// <summary>
        /// Checks for symmetry, then constructs the eigenvalue decomposition.
        /// </summary>
        /// <param name="m">a square matrix</param>
		public EigenvalueDecomposition(double[][] matrix) : base(matrix)
		{
            if (!MatrixDouble.IsSquare(matrix))
                throw new ArgumentException("Matrix must be square.");

            _v = new double[_n][];
            for (int i = 0; i < _n; i++)
                _v[i] = new double[_n];
            _real = new double[_n];
            _imaginary = new double[_n];
            _isSymmetric = MatrixDouble.IsSymmetric(matrix);

            InitializeV(matrix);
		}

        private void InitializeV(double[][] a)
        {
            int i, j;

            if (_isSymmetric)
            {
                for (i = 0; i < _n; i++)
                    for (j = 0; j < _n; j++)
                        _v[i][j] = a[i][j];

                Tridiagonalize();
                Diagonalize();
            }
            else
            {
                _hessenberg = new double[_n][];
                for (i = 0; i < _n; i++)
                    _hessenberg[i] = new double[_n];

                _ortho = new double[_n];

                for (j = 0; j < _n; j++)
                    for (i = 0; i < _n; i++)
                        _hessenberg[i][j] = a[i][j];

                Hessenberg(); // reduce to Hessenberg form.
                RealSchur(); // reduce Hessenberg to _real Schur form.
            }
        }

		#endregion

		#region Private Methods

        /// <summary>
        /// Symmetric Householder reduction to tridiagonal form.
        /// </summary>
        private void Tridiagonalize()
		{
            // Symmetric Householder reduction to tridiagonal form.
            // This is derived from the Algol procedures tred2 by Bowdler, Martin, Reinsch, and Wilkinson, 
            // Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the corresponding Fortran subroutine in EISPACK.
            for (int j = 0; j < _n; j++)
                _real[j] = _v[_n - 1][j];

            // Householder reduction to tridiagonal form.
            for (int i = _n - 1; i > 0; i--)
            {
                // Scale to avoid under/overflow.
                double scale = 0.0;
                double h = 0.0;
                for (int k = 0; k < i; k++)
                    scale = scale + Math.Abs(_real[k]);

                if (scale == 0.0)
                {
                    _imaginary[i] = _real[i - 1];
                    for (int j = 0; j < i; j++)
                    {
                        _real[j] = _v[i - 1][j];
                        _v[i][j] = 0.0;
                        _v[j][i] = 0.0;
                    }
                }
                else
                {
                    // Generate Householder vector.
                    for (int k = 0; k < i; k++)
                    {
                        _real[k] /= scale;
                        h += _real[k] * _real[k];
                    }

                    double f = _real[i - 1];
                    double g = Math.Sqrt(h);
                    if (f > 0) g = -g;

                    _imaginary[i] = scale * g;
                    h = h - f * g;
                    _real[i - 1] = f - g;
                    for (int j = 0; j < i; j++)
                        _imaginary[j] = 0.0;

                    // Apply similarity transformation to remaining columns.
                    for (int j = 0; j < i; j++)
                    {
                        f = _real[j];
                        _v[j][i] = f;
                        g = _imaginary[j] + _v[j][j] * f;
                        for (int k = j + 1; k <= i - 1; k++)
                        {
                            g += _v[k][j] * _real[k];
                            _imaginary[k] += _v[k][j] * f;
                        }
                        _imaginary[j] = g;
                    }

                    f = 0.0;
                    for (int j = 0; j < i; j++)
                    {
                        _imaginary[j] /= h;
                        f += _imaginary[j] * _real[j];
                    }

                    double hh = f / (h + h);
                    for (int j = 0; j < i; j++)
                        _imaginary[j] -= hh * _real[j];

                    for (int j = 0; j < i; j++)
                    {
                        f = _real[j];
                        g = _imaginary[j];
                        for (int k = j; k <= i - 1; k++)
                            _v[k][j] -= (f * _imaginary[k] + g * _real[k]);

                        _real[j] = _v[i - 1][j];
                        _v[i][j] = 0.0;
                    }
                }
                _real[i] = h;
            }

            // Accumulate transformations.
            for (int i = 0; i < _n - 1; i++)
            {
                _v[_n - 1][i] = _v[i][i];
                _v[i][i] = 1.0;
                double h = _real[i + 1];
                if (h != 0.0)
                {
                    for (int k = 0; k <= i; k++)
                        _real[k] = _v[k][i + 1] / h;

                    for (int j = 0; j <= i; j++)
                    {
                        double g = 0.0;
                        for (int k = 0; k <= i; k++)
                            g += _v[k][i + 1] * _v[k][j];
                        for (int k = 0; k <= i; k++)
                            _v[k][j] -= g * _real[k];
                    }
                }

                for (int k = 0; k <= i; k++)
                    _v[k][i + 1] = 0.0;
            }

            for (int j = 0; j < _n; j++)
            {
                _real[j] = _v[_n - 1][j];
                _v[_n - 1][j] = 0.0;
            }

            _v[_n - 1][_n - 1] = 1.0;
            _imaginary[0] = 0.0;
		}

        /// <summary>
        /// Symmetric tridiagonal QL algorithm.
        /// </summary>
        private void Diagonalize()
		{
            // Symmetric tridiagonal QL algorithm.
            // This is derived from the Algol procedures tql2, by Bowdler, Martin, Reinsch, and Wilkinson, 
            // Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the corresponding Fortran subroutine in EISPACK.
            for (int i = 1; i < _n; i++)
                _imaginary[i - 1] = _imaginary[i];

            _imaginary[_n - 1] = 0.0;

            double f = 0.0;
            double tst1 = 0.0;
            double eps = Math.Pow(2.0, -52.0);

            for (int l = 0; l < _n; l++)
            {
                // Find small subdiagonal element.
                tst1 = Math.Max(tst1, Math.Abs(_real[l]) + Math.Abs(_imaginary[l]));
                int m = l;
                while (m < _n)
                {
                    if (Math.Abs(_imaginary[m]) <= eps * tst1)
                        break;
                    m++;
                }

                // If m == l, _real[l] is an eigenvalue, otherwise, iterate.
                if (m > l)
                {
                    int iter = 0;
                    do
                    {
                        iter = iter + 1;  // (Could check iteration count here.)

                        // Compute implicit shift
                        double g = _real[l];
                        double p = (_real[l + 1] - g) / (2.0 * _imaginary[l]);
                        double r = Functions.GeometryFunctions.Hypot(p, 1.0);
                        if (p < 0)
                        {
                            r = -r;
                        }

                        _real[l] = _imaginary[l] / (p + r);
                        _real[l + 1] = _imaginary[l] * (p + r);
                        double dl1 = _real[l + 1];
                        double h = g - _real[l];
                        for (int i = l + 2; i < _n; i++)
                        {
                            _real[i] -= h;
                        }

                        f = f + h;

                        // Implicit QL transformation.
                        p = _real[m];
                        double c = 1.0;
                        double c2 = c;
                        double c3 = c;
                        double el1 = _imaginary[l + 1];
                        double s = 0.0;
                        double s2 = 0.0;
                        for (int i = m - 1; i >= l; i--)
                        {
                            c3 = c2;
                            c2 = c;
                            s2 = s;
                            g = c * _imaginary[i];
                            h = c * p;
                            r = Functions.GeometryFunctions.Hypot(p, _imaginary[i]);
                            _imaginary[i + 1] = s * r;
                            s = _imaginary[i] / r;
                            c = p / r;
                            p = c * _real[i] - s * g;
                            _real[i + 1] = h + s * (c * g + s * _real[i]);

                            // Accumulate transformation.
                            for (int k = 0; k < _n; k++)
                            {
                                h = _v[k][i + 1];
                                _v[k][i + 1] = s * _v[k][i] + c * h;
                                _v[k][i] = c * _v[k][i] - s * h;
                            }
                        }

                        p = -s * s2 * c3 * el1 * _imaginary[l] / dl1;
                        _imaginary[l] = s * p;
                        _real[l] = c * p;

                        // Check for convergence.
                    }
                    while (Math.Abs(_imaginary[l]) > eps * tst1);
                }
                _real[l] = _real[l] + f;
                _imaginary[l] = 0.0;
            }

            // Sort eigenvalues and corresponding vectors.
            for (int i = 0; i < _n - 1; i++)
            {
                int k = i;
                double p = _real[i];
                for (int j = i + 1; j < _n; j++)
                {
                    if (_real[j] < p)
                    {
                        k = j;
                        p = _real[j];
                    }
                }

                if (k != i)
                {
                    _real[k] = _real[i];
                    _real[i] = p;
                    for (int j = 0; j < _n; j++)
                    {
                        p = _v[j][i];
                        _v[j][i] = _v[j][k];
                        _v[j][k] = p;
                    }
                }
            }
		}

        /// <summary>
        /// Nonsymmetric reduction to Hessenberg form.
        /// </summary>
        private void Hessenberg()
		{
            // Nonsymmetric reduction to Hessenberg form.
            // This is derived from the Algol procedures orthes and ortran, by Martin and Wilkinson, 
            // Handbook for Auto. Comp., Vol.ii-Linear Algebra, and the corresponding Fortran subroutines in EISPACK.
            int low = 0;
            int high = _n - 1;

            for (int m = low + 1; m <= high - 1; m++)
            {
                // Scale column.

                double scale = 0.0;
                for (int i = m; i <= high; i++)
                    scale = scale + Math.Abs(_hessenberg[i][m - 1]);

                if (scale != 0.0)
                {
                    // Compute Householder transformation.
                    double h = 0.0;
                    for (int i = high; i >= m; i--)
                    {
                        _ortho[i] = _hessenberg[i][m - 1] / scale;
                        h += _ortho[i] * _ortho[i];
                    }

                    double g = Math.Sqrt(h);
                    if (_ortho[m] > 0) g = -g;

                    h = h - _ortho[m] * g;
                    _ortho[m] = _ortho[m] - g;

                    // Apply Householder similarity transformation
                    // H = (I - u * u' / h) * H * (I - u * u') / h)
                    for (int j = m; j < _n; j++)
                    {
                        double f = 0.0;
                        for (int i = high; i >= m; i--)
                            f += _ortho[i] * _hessenberg[i][j];

                        f = f / h;
                        for (int i = m; i <= high; i++)
                            _hessenberg[i][j] -= f * _ortho[i];
                    }

                    for (int i = 0; i <= high; i++)
                    {
                        double f = 0.0;
                        for (int j = high; j >= m; j--)
                            f += _ortho[j] * _hessenberg[i][j];

                        f = f / h;
                        for (int j = m; j <= high; j++)
                            _hessenberg[i][j] -= f * _ortho[j];
                    }

                    _ortho[m] = scale * _ortho[m];
                    _hessenberg[m][m - 1] = scale * g;
                }
            }

            // Accumulate transformations (Algol's ortran).
            for (int i = 0; i < _n; i++)
                for (int j = 0; j < _n; j++)
                    _v[i][j] = (i == j ? 1.0 : 0.0);

            for (int m = high - 1; m >= low + 1; m--)
            {
                if (_hessenberg[m][m - 1] != 0.0)
                {
                    for (int i = m + 1; i <= high; i++)
                        _ortho[i] = _hessenberg[i][m - 1];

                    for (int j = m; j <= high; j++)
                    {
                        double g = 0.0;
                        for (int i = m; i <= high; i++)
                            g += _ortho[i] * _v[i][j];

                        // Double division avoids possible underflow.
                        g = (g / _ortho[m]) / _hessenberg[m][m - 1];
                        for (int i = m; i <= high; i++)
                            _v[i][j] += g * _ortho[i];
                    }
                }
            }
		}

        /// <summary>
        /// Nonsymmetric reduction from Hessenberg to _real Schur form.
        /// </summary>
        private void RealSchur()
		{
            // Nonsymmetric reduction from Hessenberg to _real Schur form.   
            // This is derived from the Algol procedure hqr2, by Martin and Wilkinson, Handbook for Auto. Comp.,
            // Vol.ii-Linear Algebra, and the corresponding  Fortran subroutine in EISPACK.
            int nn = _n;
            int n = nn - 1;
            int low = 0;
            int high = nn - 1;
            double eps = Math.Pow(2.0, -52.0);
            double exshift = 0.0;
            double p = 0;
            double q = 0;
            double r = 0;
            double s = 0;
            double z = 0;
            double t;
            double w;
            double x;
            double y;

            // Store roots isolated by balanc and compute matrix norm
            double norm = 0.0;
            for (int i = 0; i < nn; i++)
            {
                if (i < low | i > high)
                {
                    _real[i] = _hessenberg[i][i];
                    _imaginary[i] = 0.0;
                }

                for (int j = Math.Max(i - 1, 0); j < nn; j++)
                    norm = norm + Math.Abs(_hessenberg[i][j]);
            }

            // Outer loop over eigenvalue index
            int iter = 0;
            while (n >= low)
            {
                // Look for single small sub-diagonal element
                int l = n;
                while (l > low)
                {
                    s = Math.Abs(_hessenberg[l - 1][l - 1]) + Math.Abs(_hessenberg[l][l]);
                    if (s == 0.0) s = norm;
                    if (Math.Abs(_hessenberg[l][l - 1]) < eps * s)
                        break;

                    l--;
                }

                // Check for convergence
                if (l == n)
                {
                    // One root found
                    _hessenberg[n][n] = _hessenberg[n][n] + exshift;
                    _real[n] = _hessenberg[n][n];
                    _imaginary[n] = 0.0;
                    n--;
                    iter = 0;
                }
                else if (l == n - 1)
                {
                    // Two roots found
                    w = _hessenberg[n][n - 1] * _hessenberg[n - 1][n];
                    p = (_hessenberg[n - 1][n - 1] - _hessenberg[n][n]) / 2.0;
                    q = p * p + w;
                    z = Math.Sqrt(Math.Abs(q));
                    _hessenberg[n][n] = _hessenberg[n][n] + exshift;
                    _hessenberg[n - 1][n - 1] = _hessenberg[n - 1][n - 1] + exshift;
                    x = _hessenberg[n][n];

                    if (q >= 0)
                    {
                        // Real pair
                        z = (p >= 0) ? (p + z) : (p - z);
                        _real[n - 1] = x + z;
                        _real[n] = _real[n - 1];
                        if (z != 0.0)
                            _real[n] = x - w / z;
                        _imaginary[n - 1] = 0.0;
                        _imaginary[n] = 0.0;
                        x = _hessenberg[n][n - 1];
                        s = Math.Abs(x) + Math.Abs(z);
                        p = x / s;
                        q = z / s;
                        r = Math.Sqrt(p * p + q * q);
                        p = p / r;
                        q = q / r;

                        // Row modification
                        for (int j = n - 1; j < nn; j++)
                        {
                            z = _hessenberg[n - 1][j];
                            _hessenberg[n - 1][j] = q * z + p * _hessenberg[n][j];
                            _hessenberg[n][j] = q * _hessenberg[n][j] - p * z;
                        }

                        // Column modification
                        for (int i = 0; i <= n; i++)
                        {
                            z = _hessenberg[i][n - 1];
                            _hessenberg[i][n - 1] = q * z + p * _hessenberg[i][n];
                            _hessenberg[i][n] = q * _hessenberg[i][n] - p * z;
                        }

                        // Accumulate transformations
                        for (int i = low; i <= high; i++)
                        {
                            z = _v[i][n - 1];
                            _v[i][n - 1] = q * z + p * _v[i][n];
                            _v[i][n] = q * _v[i][n] - p * z;
                        }
                    }
                    else
                    {
                        // Complex pair
                        _real[n - 1] = x + p;
                        _real[n] = x + p;
                        _imaginary[n - 1] = z;
                        _imaginary[n] = -z;
                    }

                    n = n - 2;
                    iter = 0;
                }
                else
                {
                    // No convergence yet	 

                    // Form shift
                    x = _hessenberg[n][n];
                    y = 0.0;
                    w = 0.0;
                    if (l < n)
                    {
                        y = _hessenberg[n - 1][n - 1];
                        w = _hessenberg[n][n - 1] * _hessenberg[n - 1][n];
                    }

                    // Wilkinson's original ad hoc shift
                    if (iter == 10)
                    {
                        exshift += x;
                        for (int i = low; i <= n; i++)
                            _hessenberg[i][i] -= x;

                        s = Math.Abs(_hessenberg[n][n - 1]) + Math.Abs(_hessenberg[n - 1][n - 2]);
                        x = y = 0.75 * s;
                        w = -0.4375 * s * s;
                    }

                    // MATLAB's new ad hoc shift
                    if (iter == 30)
                    {
                        s = (y - x) / 2.0;
                        s = s * s + w;
                        if (s > 0)
                        {
                            s = Math.Sqrt(s);
                            if (y < x) s = -s;
                            s = x - w / ((y - x) / 2.0 + s);
                            for (int i = low; i <= n; i++)
                                _hessenberg[i][i] -= s;
                            exshift += s;
                            x = y = w = 0.964;
                        }
                    }

                    iter = iter + 1;

                    // Look for two consecutive small sub-diagonal elements
                    int m = n - 2;
                    while (m >= l)
                    {
                        z = _hessenberg[m][m];
                        r = x - z;
                        s = y - z;
                        p = (r * s - w) / _hessenberg[m + 1][m] + _hessenberg[m][m + 1];
                        q = _hessenberg[m + 1][m + 1] - z - r - s;
                        r = _hessenberg[m + 2][m + 1];
                        s = Math.Abs(p) + Math.Abs(q) + Math.Abs(r);
                        p = p / s;
                        q = q / s;
                        r = r / s;
                        if (m == l)
                            break;
                        if (Math.Abs(_hessenberg[m][m - 1]) * (Math.Abs(q) + Math.Abs(r)) < eps * (Math.Abs(p) * (Math.Abs(_hessenberg[m - 1][m - 1]) + Math.Abs(z) + Math.Abs(_hessenberg[m + 1][m + 1]))))
                            break;
                        m--;
                    }

                    for (int i = m + 2; i <= n; i++)
                    {
                        _hessenberg[i][i - 2] = 0.0;
                        if (i > m + 2)
                            _hessenberg[i][i - 3] = 0.0;
                    }

                    // Double QR step involving rows l:n and columns m:n
                    for (int k = m; k <= n - 1; k++)
                    {
                        bool notlast = (k != n - 1);
                        if (k != m)
                        {
                            p = _hessenberg[k][k - 1];
                            q = _hessenberg[k + 1][k - 1];
                            r = (notlast ? _hessenberg[k + 2][k - 1] : 0.0);
                            x = Math.Abs(p) + Math.Abs(q) + Math.Abs(r);
                            if (x != 0.0)
                            {
                                p = p / x;
                                q = q / x;
                                r = r / x;
                            }
                        }

                        if (x == 0.0) break;

                        s = Math.Sqrt(p * p + q * q + r * r);
                        if (p < 0) s = -s;

                        if (s != 0)
                        {
                            if (k != m)
                                _hessenberg[k][k - 1] = -s * x;
                            else
                                if (l != m)
                                    _hessenberg[k][k - 1] = -_hessenberg[k][k - 1];

                            p = p + s;
                            x = p / s;
                            y = q / s;
                            z = r / s;
                            q = q / p;
                            r = r / p;

                            // Row modification
                            for (int j = k; j < nn; j++)
                            {
                                p = _hessenberg[k][j] + q * _hessenberg[k + 1][j];
                                if (notlast)
                                {
                                    p = p + r * _hessenberg[k + 2][j];
                                    _hessenberg[k + 2][j] = _hessenberg[k + 2][j] - p * z;
                                }

                                _hessenberg[k][j] = _hessenberg[k][j] - p * x;
                                _hessenberg[k + 1][j] = _hessenberg[k + 1][j] - p * y;
                            }

                            // Column modification
                            for (int i = 0; i <= Math.Min(n, k + 3); i++)
                            {
                                p = x * _hessenberg[i][k] + y * _hessenberg[i][k + 1];
                                if (notlast)
                                {
                                    p = p + z * _hessenberg[i][k + 2];
                                    _hessenberg[i][k + 2] = _hessenberg[i][k + 2] - p * r;
                                }

                                _hessenberg[i][k] = _hessenberg[i][k] - p;
                                _hessenberg[i][k + 1] = _hessenberg[i][k + 1] - p * q;
                            }

                            // Accumulate transformations
                            for (int i = low; i <= high; i++)
                            {
                                p = x * _v[i][k] + y * _v[i][k + 1];
                                if (notlast)
                                {
                                    p = p + z * _v[i][k + 2];
                                    _v[i][k + 2] = _v[i][k + 2] - p * r;
                                }

                                _v[i][k] = _v[i][k] - p;
                                _v[i][k + 1] = _v[i][k + 1] - p * q;
                            }
                        }
                    }
                }
            }

            // Backsubstitute to find vectors of upper triangular form
            if (norm == 0.0)
            {
                return;
            }

            for (n = nn - 1; n >= 0; n--)
            {
                p = _real[n];
                q = _imaginary[n];

                // Real vector
                if (q == 0)
                {
                    int l = n;
                    _hessenberg[n][n] = 1.0;
                    for (int i = n - 1; i >= 0; i--)
                    {
                        w = _hessenberg[i][i] - p;
                        r = 0.0;
                        for (int j = l; j <= n; j++)
                            r = r + _hessenberg[i][j] * _hessenberg[j][n];

                        if (_imaginary[i] < 0.0)
                        {
                            z = w;
                            s = r;
                        }
                        else
                        {
                            l = i;
                            if (_imaginary[i] == 0.0)
                            {
                                _hessenberg[i][n] = (w != 0.0) ? (-r / w) : (-r / (eps * norm));
                            }
                            else
                            {
                                // Solve _real equations
                                x = _hessenberg[i][i + 1];
                                y = _hessenberg[i + 1][i];
                                q = (_real[i] - p) * (_real[i] - p) + _imaginary[i] * _imaginary[i];
                                t = (x * s - z * r) / q;
                                _hessenberg[i][n] = t;
                                _hessenberg[i + 1][n] = (Math.Abs(x) > Math.Abs(z)) ? ((-r - w * t) / x) : ((-s - y * t) / z);
                            }

                            // Overflow control
                            t = Math.Abs(_hessenberg[i][n]);
                            if ((eps * t) * t > 1)
                                for (int j = i; j <= n; j++)
                                    _hessenberg[j][n] = _hessenberg[j][n] / t;
                        }
                    }
                }
                else if (q < 0)
                {
                    // Complex vector
                    int l = n - 1;

                    // Last vector component _imaginary so matrix is triangular
                    if (Math.Abs(_hessenberg[n][n - 1]) > Math.Abs(_hessenberg[n - 1][n]))
                    {
                        _hessenberg[n - 1][n - 1] = q / _hessenberg[n][n - 1];
                        _hessenberg[n - 1][n] = -(_hessenberg[n][n] - p) / _hessenberg[n][n - 1];
                    }
                    else
                    {
                        cdiv(0.0, -_hessenberg[n - 1][n], _hessenberg[n - 1][n - 1] - p, q);
                        _hessenberg[n - 1][n - 1] = _cdivr;
                        _hessenberg[n - 1][n] = _cdivi;
                    }

                    _hessenberg[n][n - 1] = 0.0;
                    _hessenberg[n][n] = 1.0;
                    for (int i = n - 2; i >= 0; i--)
                    {
                        double ra, sa, vr, vi;
                        ra = 0.0;
                        sa = 0.0;
                        for (int j = l; j <= n; j++)
                        {
                            ra = ra + _hessenberg[i][j] * _hessenberg[j][n - 1];
                            sa = sa + _hessenberg[i][j] * _hessenberg[j][n];
                        }

                        w = _hessenberg[i][i] - p;

                        if (_imaginary[i] < 0.0)
                        {
                            z = w;
                            r = ra;
                            s = sa;
                        }
                        else
                        {
                            l = i;
                            if (_imaginary[i] == 0)
                            {
                                cdiv(-ra, -sa, w, q);
                                _hessenberg[i][n - 1] = _cdivr;
                                _hessenberg[i][n] = _cdivi;
                            }
                            else
                            {
                                // Solve complex equations
                                x = _hessenberg[i][i + 1];
                                y = _hessenberg[i + 1][i];
                                vr = (_real[i] - p) * (_real[i] - p) + _imaginary[i] * _imaginary[i] - q * q;
                                vi = (_real[i] - p) * 2.0 * q;
                                if (vr == 0.0 & vi == 0.0)
                                    vr = eps * norm * (Math.Abs(w) + Math.Abs(q) + Math.Abs(x) + Math.Abs(y) + Math.Abs(z));
                                cdiv(x * r - z * ra + q * sa, x * s - z * sa - q * ra, vr, vi);
                                _hessenberg[i][n - 1] = _cdivr;
                                _hessenberg[i][n] = _cdivi;
                                if (Math.Abs(x) > (Math.Abs(z) + Math.Abs(q)))
                                {
                                    _hessenberg[i + 1][n - 1] = (-ra - w * _hessenberg[i][n - 1] + q * _hessenberg[i][n]) / x;
                                    _hessenberg[i + 1][n] = (-sa - w * _hessenberg[i][n] - q * _hessenberg[i][n - 1]) / x;
                                }
                                else
                                {
                                    cdiv(-r - y * _hessenberg[i][n - 1], -s - y * _hessenberg[i][n], z, q);
                                    _hessenberg[i + 1][n - 1] = _cdivr;
                                    _hessenberg[i + 1][n] = _cdivi;
                                }
                            }

                            // Overflow control
                            t = Math.Max(Math.Abs(_hessenberg[i][n - 1]), Math.Abs(_hessenberg[i][n]));
                            if ((eps * t) * t > 1)
                                for (int j = i; j <= n; j++)
                                {
                                    _hessenberg[j][n - 1] = _hessenberg[j][n - 1] / t;
                                    _hessenberg[j][n] = _hessenberg[j][n] / t;
                                }
                        }
                    }
                }
            }

            // Vectors of isolated roots
            for (int i = 0; i < nn; i++)
                if (i < low | i > high)
                    for (int j = i; j < nn; j++)
                        _v[i][j] = _hessenberg[i][j];

            // Back transformation to get eigenvectors of original matrix
            for (int j = nn - 1; j >= low; j--)
                for (int i = low; i <= high; i++)
                {
                    z = 0.0;
                    for (int k = low; k <= Math.Min(j, high); k++)
                        z = z + _v[i][k] * _hessenberg[k][j];
                    _v[i][j] = z;
                }
		}

        private void cdiv(double xr, double xi, double yr, double yi)
        {
            // Complex scalar division.
            double r;
            double d;
            if (Math.Abs(yr) > Math.Abs(yi))
            {
                r = yi / yr;
                d = yr + r * yi;
                _cdivr = (xr + r * xi) / d;
                _cdivi = (xi - r * xr) / d;
            }
            else
            {
                r = yr / yi;
                d = yi + r * yr;
                _cdivr = (r * xr + xi) / d;
                _cdivi = (r * xi - xr) / d;
            }
        }

		#endregion
	}
}